import 'package:flutter/material.dart';
import '../models/file_item.dart';
import '../models/directory_model.dart';
import '../services/file_service.dart';
import '../services/theme_service.dart';

class FileFolderListView extends StatelessWidget {
  final List<FileItem> files;
  final List<DirectoryModel> directories;
  final bool isLoading;
  final bool isSelectMode;
  final Set<int> selectedFileIds;
  final Function(int) onFileSelected;
  final Function(int, String, String) onFileTap;
  final Function(DirectoryModel) onDirectoryTap;
  final Widget? emptyWidget;
  final ScrollController? scrollController;
  final Future<void> Function()? onRefresh;
  final bool showAlternateBackground;

  const FileFolderListView({
    super.key,
    required this.files,
    required this.directories,
    required this.isLoading,
    required this.isSelectMode,
    required this.selectedFileIds,
    required this.onFileSelected,
    required this.onFileTap,
    required this.onDirectoryTap,
    this.emptyWidget,
    this.scrollController,
    this.onRefresh,
    this.showAlternateBackground = true,
  });

  // 获取文件类型对应的图标
  IconData _getIconForFile(FileItem file) {
    final fileName = file.filename.toLowerCase();
    if (fileName.isEmpty) {
      return Icons.insert_drive_file;
    }
    if (fileName.endsWith('.jpg') ||
        fileName.endsWith('.jpeg') ||
        fileName.endsWith('.png') ||
        fileName.endsWith('.gif') ||
        fileName.endsWith('.bmp') ||
        fileName.endsWith('.webp') ||
        fileName.endsWith('.heic')) {
      return Icons.image;
    } else if (fileName.endsWith('.mp4') ||
        fileName.endsWith('.avi') ||
        fileName.endsWith('.mov') ||
        fileName.endsWith('.wmv') ||
        fileName.endsWith('.flv') ||
        fileName.endsWith('.mkv')) {
      return Icons.movie;
    } else if (fileName.endsWith('.mp3') ||
        fileName.endsWith('.wav') ||
        fileName.endsWith('.ogg') ||
        fileName.endsWith('.flac') ||
        fileName.endsWith('.aac')) {
      return Icons.audio_file;
    } else if (fileName.endsWith('.pdf')) {
      return Icons.picture_as_pdf;
    } else if (fileName.endsWith('.doc') ||
        fileName.endsWith('.docx') ||
        fileName.endsWith('.txt') ||
        fileName.endsWith('.rtf')) {
      return Icons.description;
    } else if (fileName.endsWith('.xls') || fileName.endsWith('.xlsx')) {
      return Icons.table_chart;
    } else if (fileName.endsWith('.ppt') || fileName.endsWith('.pptx')) {
      return Icons.slideshow;
    } else if (fileName.endsWith('.zip') ||
        fileName.endsWith('.rar') ||
        fileName.endsWith('.7z') ||
        fileName.endsWith('.tar') ||
        fileName.endsWith('.gz')) {
      return Icons.folder_zip;
    }
    return Icons.insert_drive_file;
  }

  @override
  Widget build(BuildContext context) {
    // 如果是加载中状态，显示加载指示器
    if (isLoading && files.isEmpty && directories.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    // 准备组合列表项
    final allItems = <Widget>[];

    // 添加目录
    if (directories.isNotEmpty) {
      for (var directory in directories) {
        allItems.add(_buildDirectoryItem(context, directory));
      }
    }

    // 添加文件
    if (files.isNotEmpty) {
      for (var file in files) {
        allItems.add(_buildFileItem(context, file));
      }
    }

    // 如果没有内容，显示空状态
    if (allItems.isEmpty) {
      return emptyWidget ?? const Center(child: Text('暂无文件或文件夹'));
    }

    // 构建列表
    Widget listView = ListView.builder(
      controller: scrollController,
      itemCount: allItems.length,
      itemBuilder: (context, index) => allItems[index],
    );

    // 如果传入了刷新回调，添加下拉刷新功能
    if (onRefresh != null) {
      listView = RefreshIndicator(onRefresh: onRefresh!, child: listView);
    }

    return listView;
  }

  // 构建目录项
  Widget _buildDirectoryItem(BuildContext context, DirectoryModel directory) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      elevation: 1,
      child: ListTile(
        leading: const Icon(Icons.folder, color: Colors.amber),
        title: Text(
          directory.name,
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          '${directory.fileCount ?? 0} 个文件',
          style: const TextStyle(fontSize: 12),
        ),
        trailing: const Icon(Icons.chevron_right),
        onTap: () => onDirectoryTap(directory),
      ),
    );
  }

  // 构建文件项
  Widget _buildFileItem(BuildContext context, FileItem file) {
    final fileName = file.filename;
    final fileId = file.id;
    final fileType = file.fileType;
    final fileSize = file.formatSize();
    final fileDate = file.uploadTime;
    final isSelected = selectedFileIds.contains(fileId);

    // 为图片生成预览图
    Widget? thumbnailWidget;
    if (fileType.toLowerCase() == 'image') {
      // 简单的图标代替预览图
      thumbnailWidget = Icon(
        Icons.image,
        color: _getColorForFileType(context, fileType),
        size: 28,
      );
    }

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      elevation: 1,
      color:
          showAlternateBackground && isSelected
              ? Theme.of(context).colorScheme.primaryContainer
              : null,
      child: ListTile(
        leading:
            thumbnailWidget ??
            Icon(
              _getIconForFile(file),
              color: _getColorForFileType(context, fileType),
            ),
        title: Text(fileName, maxLines: 1, overflow: TextOverflow.ellipsis),
        subtitle: Text(
          '$fileSize・$fileDate',
          style: const TextStyle(fontSize: 12),
        ),
        trailing:
            isSelectMode
                ? Checkbox(
                  value: isSelected,
                  onChanged: (value) => onFileSelected(fileId),
                )
                : const Icon(Icons.more_vert),
        onTap:
            isSelectMode
                ? () => onFileSelected(fileId)
                : () => onFileTap(fileId, fileName, fileType),
      ),
    );
  }

  // 获取文件类型对应的颜色
  Color _getColorForFileType(BuildContext context, String fileType) {
    final theme = Theme.of(context);
    if (fileType.toLowerCase() == 'image') {
      return theme.primaryColor;
    } else if (fileType.toLowerCase() == 'video') {
      return Colors.pinkAccent;
    } else if (fileType.toLowerCase() == 'audio') {
      return Colors.purpleAccent;
    } else if (fileType.toLowerCase() == 'document') {
      return Colors.deepPurpleAccent;
    } else {
      return Colors.teal;
    }
  }
}
